/*
 * @Author: namelll 2677065112@qq.com
 * @Date: 2023-06-02 14:55:39
 * @LastEditors: namelll 2677065112@qq.com
 * @LastEditTime: 2023-06-07 15:33:04
 * @FilePath: \vue3-ts-project\src\utils\request.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
//引入axios进行二次封装：使用请求拦截器和响应拦截器
import axios from 'axios' 
import {ElMessage} from 'element-plus'
//引入用户仓库
import useUserStore from '@/store/modules/user';
//创建axios实例
let request = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,//基础路径后携带/api
    timeout: 6000
})

//请求拦截器
request.interceptors.request.use(config => {
    //获取用户仓库中的token
    let userStore = useUserStore();
    if(userStore.token){
        config.headers.token = userStore.token
    }
    // console.log("config",config)
    return config;//配置对象
});
//响应拦截器
request.interceptors.response.use((response) => {
    // console.log("response.data",response.data)
    return response.data;
}, (error) => {
    //处理网络错误
    let msg = '';
    let status = error.response.status;
    switch (status) {
        case 401:
            msg = "token过期";
            break;
        case 403:
            msg = '无权访问';
            break;
        case 404:
            msg = "请求地址错误";
            break;
        case 500:
            msg = "服务器出现问题";
            break;
        default:
            msg = "无网络";
    }
    ElMessage({
        type: 'error',
        message: msg
    })
    return Promise.reject(error);//失败的回调需要返回promise对象
});
export default request;